package com.gaax.gateway;


import com.gqqx.common.constans.RedisPrefix;
import com.gqqx.common.exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

//自定义token工厂
@Component //代表在工厂中创建对象 @configuration 配置
public class TokenGatewayFilterFactory extends AbstractGatewayFilterFactory<TokenGatewayFilterFactory.Config> {

    private RedisTemplate redisTemplate;

    @Autowired
    public TokenGatewayFilterFactory(RedisTemplate redisTemplate){
        super(Config.class);
        this.redisTemplate = redisTemplate;

    }

    @Override
    public GatewayFilter apply(Config config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                // 1.获取请求参数
                ServerHttpRequest request = exchange.getRequest();
                MultiValueMap<String, String> params = request.getQueryParams();
                if (params.getFirst("id") == null) throw new CustomException("没有id");
                String id = params.getFirst("id");
                System.out.println(id);
                System.out.println(redisTemplate.opsForValue().get(RedisPrefix.ID_KEY + id));
                //根据id信息去redis获取
                if (!redisTemplate.hasKey(RedisPrefix.ID_KEY + id)) throw new CustomException("id不合法");
                return chain.filter(exchange);
            }
        };
    }


    @Override
    public List<String> shortcutFieldOrder(){
        return super.shortcutFieldOrder();
    }



    public static class Config{

    }
}
